﻿using System;
using System.Collections.Concurrent;
using System.Diagnostics;

namespace zijian666.Core
{
    class Error2DiagnosticSource : IObserver<ErrorInfo>
    {
        public static Error2DiagnosticSource Instance { get; } = new Error2DiagnosticSource();

        public void OnCompleted() { }

        public void OnError(Exception value)
        {
            if (_listener.IsEnabled("Error"))
            {
                _listener.Write("Error", value);
            }
        }

        private readonly DiagnosticListener _listener = new DiagnosticListener(typeof(Error2DiagnosticSource).FullName);
        private readonly ConcurrentDictionary<string, DiagnosticListener> _listeners = new ConcurrentDictionary<string, DiagnosticListener>();

        public void OnNext(ErrorInfo value)
        {
            var key = value.Owner.FullName;
            if (key != null)
            {
                var listener = _listeners.GetOrAdd(key, x => new DiagnosticListener(x));
                if (listener.IsEnabled("Error"))
                {
                    listener.Write("Error", value);
                }
            }
        }
    }
}
